<template>
  <div>
    <el-dialog width="70%" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <span slot="title">
        <i class="iconfont icon-rizhi"></i>
        <span>{{title}}</span>
      </span>
      <div class="WholeScroll" style="max-height: 65vh;overflow-y: auto;overflow-x: hidden" v-loading="isLoading" element-loading-text="电子日志生成中，请稍后..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules" class="measurepaycompensation_detail_form">
          <el-row>
            <el-col :span="12">
              <el-form-item label="公司" prop="companyId" :label-width="formlabelWidth">
                <el-select style="margin: 0; margin-right: 15px;width: 100%" class="select" size="small" v-model="formBaseData.companyId" :disabled="detailType === 'check'||detailType === 'approve'||detailType==='deal'||detailType==='stamp'" v-on:change="getProjectByCompanyId()" value-key="id" placeholder="选择公司" clearable>
                  <el-option v-for="item in companyTree" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目" prop="projectId" :label-width="formlabelWidth">
                <el-select style="margin: 0; margin-right: 15px;width: 100%" class="select" size="small" v-model="formBaseData.projectId" :disabled="detailType === 'check'||detailType === 'approve'||detailType==='deal'||detailType==='stamp'" v-on:change="getSectionByProjectId()" value-key="id" filterable placeholder="选择项目" clearable>
                  <el-option v-for="item in projectTree" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="监理合同段" prop="contractId" :label-width="formlabelWidth">
                <el-select style="margin: 0; margin-right: 15px;width: 100%" class="select" size="small" @change="changeSectionInfo" v-model="formBaseData.contractId" :disabled="detailType === 'check'||detailType === 'approve'||detailType==='deal'||detailType==='stamp'" placeholder="选择监理合同段" clearable>
                  <el-option v-for="item in contractTree" :key="item.id" :label="item.numberName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="标段" prop="sectionId" :label-width="formlabelWidth">
                <el-select style="margin: 0; margin-right: 15px;width: 100%" class="select" size="small" @change="changeSectionInfoNew" v-model="formBaseData.sectionId" :disabled="detailType === 'check'||detailType === 'approve'||detailType==='deal'||detailType==='stamp'" placeholder="选择标段" clearable>
                  <el-option v-for="item in sectionTree" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item class="" label="模板名称" prop="templateName" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.templateName" placeholder="" :disabled="true"></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item class="" label="日志日期" prop="logDate" :label-width="formlabelWidth">
                <el-date-picker v-model="formBaseData.logDate" type="date" style="width:100%" format='yyyy-MM-dd' :picker-options="pickerOptions0" value-format='yyyy-MM-dd' placeholder="选择日期" :disabled="detailType === 'check' || detailType === 'approve'">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item class="whole-line" label="记录人" prop="constrUser" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.constrUser" placeholder="" :disabled="detailType === 'check'|| detailType === 'approve' "></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="" label="编号" prop="logNumber" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.logNumber" placeholder="" :disabled="detailType === 'check'|| detailType === 'approve' "></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item class="" label="施工单位" prop="constrCompanyName" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.constrCompanyName" :disabled="true "></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="" label="监理单位" prop="supervisorCompanyName" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.supervisorCompanyName" placeholder="" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item class="" label="工程名称" prop="engineeringName" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.engineeringName" placeholder="填写工程名称" :disabled="detailType === 'check'|| detailType === 'approve' "></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item class="" label="天气情况" required :label-width="formlabelWidth">
                <el-radio-group v-model="formBaseData.weatherChoose" size="medium" class="weatherRadio" :disabled="detailType === 'check'|| detailType === 'approve' " @change="updateData">
                  <el-radio-button label="晴"></el-radio-button>
                  <el-radio-button label="阴"></el-radio-button>
                  <el-radio-button label="雨"></el-radio-button>
                  <el-radio-button label="雪"></el-radio-button>
                  <el-radio-button label="其他"></el-radio-button>
                </el-radio-group>
                <!--    <el-select
                      style="margin: 0; margin-right: 15px;width: 100%"
                      class="select"
                      size="small"
                      v-model="formBaseData.weather"
                      :disabled="detailType === 'check'||detailType === 'approve'"
                      value-key="id"
                      filterable
                      placeholder="选择天气"
                      clearable
                    >
                      <el-option
                        v-for="item in weatherList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>-->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="" label="手动输入天气情况" required :label-width="formlabelWidth" v-show="formBaseData.weatherChoose == '其他'">
                <el-input class="input" size="small" v-model="formBaseData.weatherText" placeholder="请输入天气情况" :disabled="detailType === 'check'|| detailType === 'approve' " clearable @input="updateData"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item prop="people" label="人员情况" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="人员情况" v-model="formBaseData.people" :disabled="detailType === 'check'|| detailType === 'approve' ">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item prop="device" label="设备情况" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="设备情况" v-model="formBaseData.device" :disabled="detailType === 'check'|| detailType === 'approve' ">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item prop="constructionCondition" label="施工部位" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="施工部位" v-model="formBaseData.constructionCondition" :disabled="detailType === 'check'|| detailType === 'approve' ">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item prop="supervisionSite" label="监理旁站" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="监理旁站" v-model="formBaseData.supervisionSite" :disabled="detailType === 'check'|| detailType === 'approve' ">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item prop="supervisionCheck" label="监理巡查" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="监理巡查" v-model="formBaseData.supervisionCheck" :disabled="detailType === 'check'|| detailType === 'approve' ">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="备注" v-model="formBaseData.remark" :disabled="detailType === 'check'|| detailType === 'approve' ">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!--<el-row>
             <el-col :span="12">
              <el-form-item class="whole-line" label="总监理工程师" prop="auditUser" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.auditUser" placeholder="" :disabled="detailType === 'check'|| detailType === 'approve' "></el-input>
              </el-form-item> -->
          <!--<el-form-item class="whole-line" label="审核人" prop="auditUser" :label-width="formlabelWidth">
                <el-select
                  style="margin: 0; margin-right: 15px;width: 100%"
                  class="select"
                  size="small"
                  v-model="formBaseData.auditUser"
                  :disabled="detailType === 'check'||detailType === 'approve'"
                  value-key="id"
                  filterable
                  placeholder="选择审核人"
                  clearable
                >
                  <el-option
                    v-for="item in auditUserList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> 
          </el-row>-->
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item class="" label="温度" prop="temperature" :label-width="formlabelWidth">
                <el-input size="small" type="number" v-model="formBaseData.temperature" placeholder="填写温度" :disabled="detailType === 'check'|| detailType === 'approve' "> <template slot="append">°C</template></el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item class="whole-line" label="主要施工项目简述" prop="mainConstConditions" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" size="small" :autosize="{ minRows: 4, maxRows: 6}" v-model="formBaseData.mainConstConditions" placeholder="主要施工项目简述" :disabled="detailType === 'check'|| detailType === 'approve'"></el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item prop="mainJob" label="监理机构主要工作简述" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="监理机构主要工作简述（审批、验收、旁站、指令、会议等）" v-model="formBaseData.mainJob" :disabled="detailType === 'check'|| detailType === 'approve' ">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item prop="treatment" label="有关问题澄清或处理的情况简述" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="就有关问题与建设单位、施工单位、设计单位等进行澄清或处理的情况简述" v-model="formBaseData.treatment" :disabled="detailType === 'check'|| detailType === 'approve' ">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row>
            <el-col :span="19" style="position: relative">
              <el-form-item label="现场照片" :label-width="formlabelWidth">
                <cmsUploadFileJpg ref="fileThree" :detail-id="detailId" :fileSystem="fileSystem['three']" :disabled="detailType === 'check'|| detailType === 'approve'" type="mul" :fileList="fileListThree" info="支持上传 png/jpg/gif 文件" :detail-type="detailType" />
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row>
            <el-col :span="19" style="position: relative" class="otherMeterageUpload">
              <el-form-item label="事故处理及报告" :label-width="formlabelWidth">
                <cmsUploadFile ref="fileOne" :detail-id="detailId" :fileSystem="fileSystem['one']" :disabled="detailType === 'check'|| detailType === 'approve'" type="mul" :fileList="fileList" info="支持上传 png/jpg/gif/doc/xlsx/ppt/pdf等文件" :detail-type="detailType" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <!--api操作按钮 除去上报-->
        <!--新建和编辑的暂存上报-->
        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('createFile', {flag: 1})">
            <i class="iconfont icon-icon_save"></i> 确 定</el-button>
          <!--   <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit', {flag: 1})"><i class="iconfont icon-icon_save"></i> 确 定</el-button>-->
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import projectSectionInfo from "@/api/buss/common";
import sectionInfo from "@/api/buss/sectionInfo";
import msgUtil from "@/utils/msgUtil";
import supervisorlog from "@/api/buss/supervisorlog";
import store from "@/store";
import dept from "@/api/system/dept";
import { getCompanyByContractId } from '../../../../api/buss/supervisorlog'
import file from "@/api/file";
import { Base64 } from 'js-base64'
export default {
  name: "supervisorlog-manage-detail",
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  watch: {
    postDetail(value) {
      console.log(this.formBaseData)
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      // 详情类型
      this.detailType = value.type
      if (this.detailType == 'build') {
        this.title = '新增监理日志'
        this.formBaseData.constrUser = store.getters.user.name
        this.isShowBpmn = true
      } else if (this.detailType == 'check') {
        this.title = '查看监理日志'
      } else if (this.detailType == 'edit') {
        this.isShowBpmn = true
        this.title = '编辑监理日志'
      } else if (this.detailType == 'approve') {
        this.isShowBpmn = true
        this.title = '监理日志审核'
      } else {
        this.title = ''
      }
      // 详情id
      this.detailId = value.detailId ? value.detailId : '';
      // 非新建详情时 获取详情

      if (this.detailType == 'build') {
        this.getFillUnit()
        this.$nextTick(() => {
          this.$refs['formBaseData'].resetFields()
          this.initData()
          //   this.getAuditUserList();
        })
      } else {
        // 获取详情请求
        this.initData().then(res => {
          this.getDetail()
          /*      this.getAuditUserList().then(it=>{
                  this.getDetail()
                })*/
        })

      }
    }
  },
  data() {
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      fileList: [],
      fileListThree: [],
      companyTree: [], // 公司下拉
      projectTree: [], // 项目下拉
      sectionTree: [],
      contractTree: [], // 合同段下拉
      checkInitShow: false,
      isLoading: false,
      actionType: '查看',
      title: '监理日志',
      isYz: false,//上报人公司类型 是否是业主
      //存放图片的数组
      fileListArray: [],
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      activeName: 'first', //
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      radioValue: '',//单选按钮选中的值
      formlabelWidth: '160px', // 表单左侧标题宽度
      selectList: {
        file: [], // 文件
        approver: [], // 审批人
        structureType: [], // 结构类型
      },
      fileSystem: {
        'one': {
          sys: 'buss',
          module: 'supervisorlog',
          part: 'one',
          compoName: 'fileOne'
        },
        // 'three': {
        //   sys: 'buss',
        //   module: 'supervisorlog',
        //   part: 'three',
        //   compoName: 'fileThree'
        // }
      }, // 文件系统的参数
      // 所有下拉框列表的集合
      // 表单基本信息内容
      formBaseData: {
        companyId: '',
        contractId: '',
        sectionId: '',
        projectId: '',
        projectResume: '',
        constrCompany: '',//施工单位
        constrCompanyName: '',//施工单位
        supervisorCompany: '',//监理单位
        supervisorCompanyName: '',//监理单位
        logNumber: new Date().Format("yyyyMMdd"),//日志编号
        logDate: new Date().Format("yyyy-MM-dd"),//施工日志日期
        constrUser: '',//记录人
        contractName: '',
        projectName: '',//工程名称
        constrRemark: '',//备注
        log: [], // 日志
        fillUnit: '',
        auditUser: '',
        templateName: '监理日志（JTGG10-2016）',
        engineeringName: '',
        temperature: '',
        weather: '晴',
        mainConstConditions: '',
        mainJob: '',
        treatment: '',
        isCreateFile: '',
        weatherChoose: '晴',
        content: '',
        weatherText: '晴',
        people: '',
        device: '',
        constructionCondition: '',
        supervisionSite: '',
        supervisionCheck: '',
        remark: ''
      },
      weatherList: [{ label: '晴', value: '晴' }, { label: '阴', value: '阴' }, { label: '雨', value: '雨' }, { label: '雪', value: '雪' }],
      // 表单基本信息验证
      formBaseRules: {
        companyId: [
          { required: true, message: '请选择' + '公司', trigger: 'change' },
        ],
        projectId: [
          { required: true, message: '请选择' + '项目', trigger: 'change' },
        ],
        sectionId: [
          { required: true, message: '请选择' + '标段', trigger: 'change' },
        ],
        contractId: [
          { required: true, message: '请选择' + '监理合同段', trigger: 'change' },
        ],
        logNumber: [
          { required: true, message: '请输入' + '日志编号', trigger: 'change' },
        ],
        logDate: [
          { required: true, message: '请输入' + '日志日期', trigger: 'blur' },
        ],
        constrUser: [
          { required: true, message: '请选择' + '记录人', trigger: 'blur' },
        ],

        engineeringName: [
          { required: true, message: '请输入' + '工程项目', trigger: 'change' },
        ],
        weather: [
          { required: true, message: '请选择' + '天气情况', trigger: 'blur' },
        ],
        mainConstConditions: [
          { required: true, message: '请输入' + '主要施工项目简述', trigger: 'blur' },
        ],
        temperature: [
          { required: true, message: '请输入' + '温度', trigger: 'change' },
        ],
        auditUser: [
          { required: true, message: '请输入' + '总监理工程师', trigger: 'change' },
        ],
        people: [
          { required: true, message: '请输入' + '人员情况', trigger: 'blur' },
        ],
        device: [
          { required: true, message: '请输入' + '设备情况', trigger: 'blur' }
        ],
        constructionCondition: [
          { required: true, message: '请输入' + '施工部位', trigger: 'blur' }
        ],
        supervisionSite: [{ required: true, message: '请输入' + '监理旁站', trigger: 'blur' }],
        supervisionCheck: [{ required: true, message: '请输入' + '监理巡查', trigger: 'blur' }]
      },
      auditUserList: [],
    }
  },
  created() {

  },
  methods: {
    updateData() {
      this.$forceUpdate()
    },
    openFile() {
      supervisorlog.getOne(this.detailId).then(res => {
        if (res.code == 200) {
          let fileId = res.data.fileId
          this.viewFile(fileId)
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("打开文件失败")
      })
    },
    viewFile(e) {
      this.loading = true
      file.preview(e).then(response => {
        //  如果是minio地址路径，则调用kkview
        if (!response.data.startsWith("/")) {
          window.open(PREVIEW_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(response.data)));
        } else {
          //  如果是转换后的previewGetFile，浏览器直接打开
          window.open(response.data);
        }
        this.loading = false
      })
    },
    getAuditUserList() {
      return supervisorlog.getAuditUserList({}).then(res => {
        if (res.code === 200) {
          var data = res.data;
          this.auditUserList = data
          return new Promise(resolve => {
            resolve(res)
          })
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取审批人失败")
      })
    },
    getFillUnit() {
      supervisorlog.getFillUnit({}).then(res => {
        if (res.code === 200) {
          var data = res.data;
          this.formBaseData.fillUnit = data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取填报单位失败")
      })
    },
    changeSectionInfoNew() {
      sectionInfo.getCompanyBySecId(this.formBaseData.sectionId).then(res => {
        if (res.status === 1) {
          var data = res.data;
          this.formBaseData.constrCompanyName = data.buildUnit
          this.formBaseData.supervisorCompanyName = data.supervisorUnit
          this.formBaseData.constrCompany = data.buildUnitId
          this.formBaseData.supervisorCompany = data.supervisorUnitId && data.supervisorUnitId.length > 0 ? data.supervisorUnitId[0] : ""
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取标段相关单位失败")
      })
    },
    changeSectionInfo() {
      let id = ''
      let coalition = ''
      this.contractTree.forEach(item => {
        if (item.id == this.formBaseData.contractId) {
          id = item.secondParty
          coalition = item.coalition
          this.formBaseData.contractName = item.numberName
        }
      })
      var ids = id.split(",")
      this.formBaseData.supervisorCompanyName = ''
      this.formBaseData.supervisorCompany = ''
      if (coalition == 1) {  //非联合体
        dept.getOne(ids[0]).then(res => {
          if (res.code === 200) {
            var data = res.data;
            this.formBaseData.supervisorCompanyName = data.simplename
            this.formBaseData.supervisorCompany = data.id
          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch(() => {
          msgUtil.error2("获取合同段相关单位失败")
        })
      } else {
        supervisorlog.getCompanyByContractId(this.formBaseData.contractId).then(res => {
          if (res.code === 200) {
            var data = res.data;
            this.formBaseData.supervisorCompanyName = data.supervisorUnit
            this.formBaseData.supervisorCompany = data.supervisorUnitId
          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch(() => {
          msgUtil.error2("获取合同段相关单位失败")
        })
      }
      if (this.detailType == 'build') {
        this.getLogNumber()
        supervisorlog.buildUnit(this.formBaseData.contractId).then(res => {
          if (res.code === 200) {
            var data = res.data;
            this.formBaseData.constrCompanyName = data.buildName
            this.formBaseData.auditUser = data.jlName
          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch(() => {
          msgUtil.error2("获取合同段施工单位失败")
        })
      }
    },
    initData() {
      this.companyTree = []
      return projectSectionInfo.getProjectSectionInfoTree().then(res => {
        if (res.code === 200) {
          var data = res.data;
          this.companyTree = data
          if (this.detailType == 'build' && this.companyTree.length > 0) {
            if (this.companyTree.length == 1) {
              this.formBaseData.companyId = this.companyTree[0].id;
            }
            this.getProjectByCompanyId()
          }
          return new Promise(resolve => {
            resolve(res)
          })
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取项目标段树失败")
      })

    },
    getLogNumber() {
      let sectionId = this.formBaseData.sectionId
      this.$httpGet('buss/commonAPI/getLogNumber?type=4&sectionId=' + sectionId).then(res => {
        if (res.code === 200) {
          this.formBaseData.logNumber = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
      })
    },

    /**
     *  根据建设单位查询下面的所有项目
     * */
    getProjectByCompanyId() {
      if (this.formBaseData.projectId && !this.checkInitShow) {
        this.formBaseData.projectId = ''
      }
      if (this.formBaseData.sectionId && !this.checkInitShow) {
        this.formBaseData.sectionId = ''
      }
      this.companyTree.forEach((item) => {
        if (item.id === this.formBaseData.companyId) {
          this.projectTree = item.children
          if (this.detailType == 'build' && this.projectTree.length > 0) {
            if (this.projectTree.length == 1) { this.formBaseData.projectId = this.projectTree[0].id; }
            this.getSectionByProjectId();
          }
        }
      })
    },

    /**
     * 根据项目id获取标段列表
     * getContractByProjectId
     * */
    getSectionByProjectId() {
      if (this.formBaseData.sectionId && !this.checkInitShow) {
        this.formBaseData.sectionId = ''
      }

      if (this.checkInitShow) {
        this.checkInitShow = false
      }
      if (this.formBaseData.projectId) {
        this.projectTree.forEach((item) => {
          if (item.id == this.formBaseData.projectId) {
            this.sectionTree = item.children
            if (this.detailType == 'build' && this.sectionTree.length > 0) {
              if (this.sectionTree.length == 1) {
                this.formBaseData.sectionId = this.sectionTree[0].id;
              }
              //获取日志编号
              if (this.detailType && this.detailType === 'build') {
                this.getLogNumber()
              }
              this.changeSectionInfoNew();
            }
          }
        })
      }
      // if (this.formBaseData.projectId) {
      //   projectSectionInfo.getContractList({ projectId: this.formBaseData.projectId }).then(res => {
      //     if (res.code === 200) {
      //       this.sectionTree = res.data;
      //       if (this.detailType == 'build' && this.sectionTree.length > 0) {
      //         this.formBaseData.sectionId = this.sectionTree[0].id;
      //         this.getLogNumber();
      //         this.changeSectionInfoNew();
      //       }

      //     } else {
      //       msgUtil.error2(res.data.message)
      //     }
      //   }).catch(() => {
      //     msgUtil.error2("获取监理合同段失败")
      //   })
      // }
    },

    // 获取详情请求 api
    getDetail() {
      supervisorlog.getOne(this.detailId).then(res => {
        if (res.code == 200) {
          this.formBaseData = res.data
          if (this.formBaseData.weather != '晴' && this.formBaseData.weather != '阴' && this.formBaseData.weather != '雨' && this.formBaseData.weather != '雪') {
            this.formBaseData.weatherChoose = '其他'
            this.formBaseData.weatherText = this.formBaseData.weather
          } else {
            this.formBaseData.weatherChoose = this.formBaseData.weather
          }
          this.checkInitShow = true
          this.getProjectByCompanyId()
          this.getSectionByProjectId()
          this.changeSectionInfoNew()
          this.loadFiles()
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败")
      })
    },
    // 提交详情 提交1/暂存0 新建0/修改1
    submitAndCreateDetail(type, callback, slient) {
      this.formBaseData.isCreateFile = '1'
      if (this.detailType === 'build') {
        this.isLoading = true
        supervisorlog.submit(this.formBaseData).then(res => {
          if (res.code === 200) {
            this.formShow = false
            this.detailId = res.data.id
            // this.openFile()
            if (callback) callback()
          } else {

            msgUtil.error2(res.data.message)
          }
        }).catch((res) => {
          console.log(res)
          // this.$notify({
          //   title: '施工安全日志保存失败',
          //   type: 'error',
          //   duration: 2500
          // })
        }).finally((response) => {
          this.isLoading = false
        })
      } else {
        this.isLoading = true
        supervisorlog.resubmit(this.formBaseData).then(res => {
          if (res.code === 200) {
            this.formShow = false
            this.detailId = res.data.id
            // this.openFile()
            if (callback) callback()
          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((res) => {
          console.log(res)
          // this.$notify({
          //   title: '施工安全日志保存失败',
          //   type: 'error',
          //   duration: 2500
          // })
        }).finally((response) => {
          this.isLoading = false
        })
      }
    },
    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback, slient) {
      if (this.detailType === 'build') {
        this.isLoading = true
        supervisorlog.submit(this.formBaseData).then(res => {
          if (res.code === 200) {
            this.formShow = false
            this.detailId = res.data.id
            if (callback) callback()
          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((res) => {
          console.log(res)
          // this.$notify({
          //   title: '监理日志保存失败',
          //   type: 'error',
          //   duration: 2500
          // })
        }).finally((response) => {
          this.isLoading = false
        })
      } else {
        this.isLoading = true
        supervisorlog.resubmit(this.formBaseData).then(res => {
          if (res.code === 200) {
            this.formShow = false
            this.detailId = res.data.id
            if (callback) callback()
          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((res) => {
          console.log(res)
          // this.$notify({
          //   title: '监理日志保存失败',
          //   type: 'error',
          //   duration: 2500
          // })
        }).finally((response) => {
          this.isLoading = false
        })
      }
    },
    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost(
        this.$store.state.httpHost.buss + url + query,
        params
      ).then(res => {
        if (res.data.status === 1) {
          if (callback) callback(res.data)
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        console.log(res)
      })
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          // 清空表单内容
          this.formBaseData = {
            companyId: '',
            contractId: '',
            sectionId: '',
            projectId: '',
            projectResume: '',
            constrCompany: '',//施工单位
            constrCompanyName: '',//施工单位
            supervisorCompany: '',//监理单位
            supervisorCompanyName: '',//监理单位
            logNumber: new Date().Format("yyyyMMdd"),//日志编号
            logDate: new Date(),//施工日志日期
            constrUser: '',//记录人
            contractName: '',
            projectName: '',//工程名称
            constrRemark: '',//备注
            log: [], // 日志
            fillUnit: '',
            auditUser: '',
            templateName: '监理日志（JTGG10-2016）',
            engineeringName: '',
            temperature: '',
            weather: '',
            mainConstConditions: '',
            mainJob: '',
            treatment: '',
            isCreateFile: '',
            people: '',
            device: '',
            constructionCondition: '',
            supervisionSite: '',
            supervisionCheck: '',
            remark: ''
          } // 表单基本信息内容
          this.fileList = []
          this.fileListThree = []

          for (let k in this.fileSystem) {
            let fileProp = this.fileSystem[k]
            this.$refs[fileProp.compoName].cancelAll()
          }
          this.companyTree = []
          this.projectTree = []
          this.sectionTree = []
          // 关闭弹窗
          this.formShow = false
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 提交详情
              // 绑定文件到表单
              // 提交详情
              this.submitDetail(flag, () => {
                this.saveFiles()
                setTimeout(() => {
                  this.$emit('reloadList')
                  this.$notify({
                    title: '监理日志保存成功',
                    type: 'success',
                    duration: 1500
                  })
                }, 1500)

              }, true)

            }
          })
          break
        case 'createFile':
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              if (this.formBaseData.weatherChoose == '其他') {
                if (this.formBaseData.weatherText) {
                  this.formBaseData.weather = this.formBaseData.weatherText
                } else {
                  msgUtil.error2("请输入天气情况");
                  return false;
                }
              } else {
                this.formBaseData.weather = this.formBaseData.weatherChoose
              }
              // 提交详情
              this.submitAndCreateDetail(flag, () => {
                this.saveFiles()
                setTimeout(() => {
                  this.$emit('reloadList')
                  this.$notify({
                    title: '监理日志保存成功',
                    type: 'success',
                    duration: 1500
                  })
                }, 1500)
              }, true)
            }
          });
          break
        // 删除
        case 'delete':
          break
      }
    },
    saveFiles() {
      for (let k in this.fileSystem) {
        let fileProp = this.fileSystem[k]
        this.$refs[fileProp.compoName].saveAll(this.detailId)
      }
    },

    loadFiles() {
      this.$nextTick(() => {
        for (let k in this.fileSystem) {
          let fileProp = this.fileSystem[k]
          this.$refs[fileProp.compoName].init()
        }
      })
    },
  },

}
</script>

<style scoped lang="scss">
.el-select.half {
  width: 250px;
}
.el-select.fill {
  width: 800px;
}

.el-input .el-select {
  width: 130px;
}
.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}
</style>
